<script setup lang='ts'>
import {getCartList, updatenum} from '../../api/cart'
import {useUserStore} from '../../stores/user'
import {ref} from 'vue'
import type {Ref} from 'vue'
import type {iCart} from './cart'
import { showFailToast } from 'vant';
const user = useUserStore()

const cartList: Ref<iCart[]> = ref([])

getCartList({
  userid: user.userid
}).then(res => {
  // console.log(res.data.data);
  cartList.value = res.data.data
})

// 更新购物车数据
function changeNum(item: iCart, type: string){
  if(type == '10010'){
    // 减
    item.num--
  }else {
    // 加
    item.num++
  }

  if(item.num == 0){
    item.num = 1
    showFailToast('购物车商量不能小于 1');
  }else {
  updatenum({
    cartid: item.cartid,
    num: item.num
  }).then(res => {
    if(res.data.code == 200){
      // 重新获取数据
      getCartList({
        userid: user.userid
      }).then(res => {
        // console.log(res.data.data);
        cartList.value = res.data.data
      })
    }
  })
  }

 
}

</script>
<template>
    <main class='box'>
      <header class='header'>
        头部-购物车
      </header>

      <div v-if="cartList.length < 1">
        <van-empty description="购物车为空" />
      </div>
      <div v-else class='content'>
        
        <van-swipe-cell v-for="item in cartList" :key="item.cartid">
         
          <van-card
            :price="item.originprice"
            :title="item.proname"
            class="goods-card"
            :thumb="item.img1"
          >
             <template #footer>
                <van-button @click='changeNum(item,"10010")' style="padding: 0 8px" size="mini"> - </van-button>
                <span class="cart-num">{{item.num}}</span>
                <van-button @click='changeNum(item,"10011")' size="mini" style="padding: 0 8px"> + </van-button>
              </template>
          </van-card>


          <template #right>
            <van-button square text="删除" type="danger" class="delete-button" />
          </template>

        </van-swipe-cell>

      </div>
    </main>
</template>
<style scoped lang="scss">
    .goods-card {
    margin: 0;
    background-color: white;
  }

  .delete-button {
    height: 100%;
  }
  .cart-num {

    display: inline-block;
    line-height: 26px;
    height: 26px;
    width: 40px;
    text-align: center;
    position: relative;
    top: 4px;
  }
</style>